<template>
  <div :class="s3Store.editStatus ? 'showroom-3d-canvas edit' : 'showroom-3d-canvas preview'">
    <div class="showroom-3d-layer-bg">
      <div class="img-center-flex">
        <img :src="previewImgBgList[sceneIndex]" alt="Centered Image">
      </div>
    </div>
    <div class="showroom-3d-layer-model" v-if="boxArr.length > 0 && isLayerModel" @click="clickModelLayer"
      v-loading="!isLayerModel">
      <DragMoveItem v-for="(item, index) in boxArr" :key="'showroom-3d-layer-model' + index" :propsAttribute="item"
        @showAttribute="showEntityAttribute" :attributeItem="JSON.stringify(item)" :modelId="item.modelId" />
    </div>
    <div class="showroom-3d-layer-modellist" v-if="s3Store.editStatus">
      <BaseDrawer :title="drawerTitle[0]" :showDrawer="isShowModellist" @closeDrawer="isShowModellist = false">
        <ModelList :selectModel="s3Store.modelObj"></ModelList>
      </BaseDrawer>
    </div>
    <div class="showroom-3d-layer-attribute" v-if="s3Store.editStatus">
      <BaseDrawer :title="drawerTitle[1]" :showDrawer="isDrawer" @closeDrawer="isDrawer = false">
        <RightAttribute :selectModel="s3Store.modelObj"></RightAttribute>
      </BaseDrawer>
    </div>
    <div class="showroom-3d-layer-operation" v-else>
      <OperationPopupWindow v-if="isDrawer" :selectModel="s3Store.modelObj" @click="clickOperationLayer">
        <el-button :loading="item.loading" class="operation-btn-box" v-for="(item, index) in opwOptionsBtn"
          :modelId="s3Store.modelId" :operationId="item.id" :operationAction="item.value"
          :key="'s-3d-l-operation' + index">{{
    item.label
  }}</el-button>
      </OperationPopupWindow>
    </div>
  </div>
</template>

<script setup>
import { Showroom3DStore } from "@/pinia/Showroom3D";
const s3Store = Showroom3DStore();
import BaseDrawer from '@/views/showroom3D/components/BaseDrawer.vue';
import DragMoveItem from '@/views/showroom3D/components/DragMoveItem.vue';
import OperationPopupWindow from '@/views/showroom3D/components/OperationPopupWindow.vue';
import RightAttribute from '@/views/showroom3D/RightAttribute.vue';
import ModelList from '@/views/showroom3D/ModelList.vue';
import previewS3dBg1 from '@/assets/img/s3d_bg01.png';
import previewS3dBg2 from '@/assets/img/s3d_bg02.jpg';
import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
import { sendActionModel } from '@/api/showroom3dApi'

let isDrawer = ref(false);
const drawerTitle = ref(['灯具模板列表', '灯具详情']);
let isShowModellist = ref(false);
const previewImgBgList = ref([previewS3dBg1, previewS3dBg2])
const htmlLog = ref([])
const isLayerModel = ref(true)

const opwOptionsBtn = computed(() => {
  if (s3Store.modelObj && s3Store.modelObj.BaseOperation) {
    return s3Store.modelObj.BaseOperation
  }
  return []
})

watch(
  () => s3Store.operationStatus,
  (nval, oldVal) => {
    if (nval) {
      switch (nval) {
        case 'save':
          saveModel()
          break;
        case 'add':
          addModel()
          break;
        case 'delete':
          deleteModel()
          break;
        case 'edit':
          editModel()
          break;
        case 'rotate':
          rotateModel()
          break;
        case 'scale':
          scaleModel()
          break;
        case 'translate':
          translateModel()
          break;
        case 'reset':
          resetModel()
          break;
        case 'copy':
          copyModel()
          break;
        case 'paste':
        default:
          break;
      }
      ElNotification({ title: '操作提示:', message: `${i18n.fy[nval]}成功`, type: 'success', duration: 3000 })
    }
  }
);

watch(
  () => s3Store.editStatus,
  (nval) => {
    isDrawer.value = false
  }
);

const clickOperationLayer = async (event) => {
  console.log('当前点击Dom', event);
  let xxx = event.target.getAttribute('class')
  console.log(xxx);
  if (xxx === "el-button operation-btn-box") {
    const mid = event.target.getAttribute('modelId')
    const oid = event.target.getAttribute('operationId')
    const action = event.target.getAttribute('operationAction')
    console.log('mid', mid);
    console.log('oid', oid);
    console.log('action', action);
    let proms = {
      deviceFid: 139,
      mesh: {
        code: "400",
        deviceName: 139,
        area: "6",
        address: "6",
        action: action,
        params: "",
        identity: ""
      }
    }
    const res = await sendActionModel(proms)
    console.log('clickOperationLayer->sendActionModel->', res);
  }
}

const clickModelLayer = (event) => {
  console.log('当前点击Dom', event);
  console.log('事件消息队列', htmlLog.value);
  for (let index = 0; index < htmlLog.value.length; index++) {
    htmlLog.value[index].className = 'drag-move-item'
  }
  let scls = event.target.getAttribute('class')
  if (!s3Store.editStatus) {
    console.log('预览状态', scls);
    isDrawer.value = false
    if (event.target) {
      if (scls === 'showroom-3d-layer-model') {
        isDrawer.value = false
      } else {
        event.target.className = 'drag-move-item selected'
        let nuuid = event.target.getAttribute('modelId')
        let ouuid = htmlLog.value[0].getAttribute('modelId')
        console.log(nuuid === ouuid, 'nuuid->', nuuid, 'ouuid->', ouuid);
        if (nuuid === ouuid) {
          isDrawer.value = true
        }
      }
    }
  } else {
    console.log('编辑状态', scls);
    if (event.target) {
      if (scls === 'drag-move-item') {
        console.log('点击的是模型', scls);
        let nuuid = event.target.getAttribute('modelId')
        let ouuid = htmlLog.value[0].getAttribute('modelId')
        console.log(nuuid === ouuid, 'nuuid->', nuuid, 'ouuid->', ouuid);
        console.log('htmlLog.value->', htmlLog.value);
        event.target.className = 'drag-move-item selected'
        if (nuuid === ouuid) {
          isDrawer.value = true
          console.log('点击的是同一个模型');
        }
      }
    }
  }
}
// 保存模型
const saveModel = () => {
  let htmlarr = window.document.getElementsByClassName('drag-move-item')
  let arr = []
  for (let i = 0; i < htmlarr.length; i++) {
    let html = JSON.parse(htmlarr[i].getAttribute('attributeItem'))
    let posxy = getStartPositionXY(htmlarr[i].getAttribute('style'))
    let obj = {
      modelId: html.modelId,
      modelName: html.modelName,
      modelUrl: html.modelUrl,
      modelType: html.modelType,
      modelStyle: html.modelStyle,
      clsName: htmlarr[i].getAttribute('class'),
      zIndex: html.zIndex,
      offsetX: htmlarr[i].offsetLeft,
      offsetY: htmlarr[i].offsetTop,
      width: htmlarr[i].offsetWidth,
      height: htmlarr[i].offsetHeight,
      positionX: posxy[0] * 1,
      positionY: posxy[1] * 1,
    }
    if (html.modelId === s3Store.modelId) {
      obj.BaseOperation = s3Store.modelObj.BaseOperation
    }
    arr.push(obj)
  }
  localStorage.setItem('CanvasBox-html-div', JSON.stringify(arr))
  window.location.reload()
}
// 删除模型
const deleteModel = () => {
  let htmlarr = window.document.getElementsByClassName('drag-move-item')
  for (let i = 0; i < htmlarr.length; i++) {
    if (htmlarr[i].className.indexOf('selected') > -1) {
      htmlarr[i].remove()
    }
  }
  console.log(s3Store.modelList.length);
  console.log(s3Store.modelId);
  let arr = []
  s3Store.modelList.forEach(element => {
    if (element.modelId !== s3Store.modelId) {
      arr.push(element)
    }
  });
  s3Store.setModelList(arr)
  console.log(s3Store.modelList.length);
}
// 添加模型
const addModel = () => {
  let obj = {
    modelId: generateUUID(),
    modelName: '新增模型' + (s3Store.modelList.length + 1),
    modelUrl: '',
    modelType: 'lamp',
    modelStyle: 'mstyle',
    clsName: 'drag-move-item',
    height: 96,
    width: 96,
    offsetX: 0,
    offsetY: 0,
    zIndex: 3,
    positionX: 0,
    positionY: 0,
    BaseOperation: []
  }
  s3Store.addModel(obj)
}
// 修改模型
const editModel = () => {
  s3Store.setOperationStatus('edit')
}

// 获取模型坐标信息
const getStartPositionXY = (str) => {
  let lightList = [0, 0];
  if (str.split('transform: translate').length > 0) {
    lightList = str.split('transform: translate')[1].match(/\d+/g);
  }
  return lightList;
}
const generateUUID = () => {
  let d = new Date().getTime();
  let d2 = (performance && performance.now && (performance.now() * 1000)) || 0;
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16;
    if (d > 0) {
      r = (d + r) % 16 | 0;
      d = Math.floor(d / 16);
    } else {
      r = (d2 + r) % 16 | 0;
      d2 = Math.floor(d2 / 16);
    }
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
}
const boxArr = computed(() => {
  return s3Store.modelList;
});
const sceneIndex = computed(() => {
  return s3Store.sceneIndex;
});

const showEntityAttribute = (entity) => {
  console.log('showEntityAttribute->', entity);
  htmlLog.value.push(entity.dom)
  if (htmlLog.value.length > 2) {
    htmlLog.value.shift()
  }
  s3Store.setModelId(entity.modelId)
}

onMounted(async () => {
  localStorage.getItem('CanvasBox-html-div') && s3Store.setModelList(JSON.parse(localStorage.getItem('CanvasBox-html-div')))
  await nextTick();
  const s = document.getElementsByClassName('selected')
  console.log('onMounted->', s, s.length);
  if (s.length > 0) {
    s3Store.setModelId(s[0].getAttribute('modelId'))
    htmlLog.value.push(s[0])
    console.log('初始化-上次选中', htmlLog.value);
  } else {
    if (s3Store.modelList.length > 0) {
      s3Store.setModelId(s3Store.modelList[0].modelId)
      console.log('初始化-默认第一', htmlLog.value);
    }
  }
});

</script>
<style lang="scss" scoped>
.preview {
  .drag-move-item:hover {
    cursor: pointer;
  }
}

.showroom-3d-canvas {
  width: 100%;
  height: 100%;
  flex: 1;
  position: relative;
}

.edit {
  .drag-move-item:hover {
    cursor: move;
  }
}

.showroom-3d-canvas {
  width: 100%;
  height: 100%;
  flex: 1;

  .showroom-3d-layer-bg {
    width: 100%;
    height: 100%;
    z-index: 1;
    position: absolute;

    .img-center-flex {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      user-select: none;
      -webkit-user-drag: none;

      img {
        user-select: none;
        -webkit-user-drag: none;
      }
    }

    .preview-s3d-bg1 {
      background: url("/src/assets/img/s3d_bg01.png") no-repeat;
      background-size: cover;
    }

    .preview-s3d-bg2 {
      background: url("/src/assets/img/s3d_bg02.jpg") no-repeat;
      background-size: cover;
    }

  }

  .showroom-3d-layer-model {
    width: 100%;
    height: 100%;
    z-index: 2;
    position: absolute;

    .box-canvas {
      width: 100%;
      height: 100%;
    }

    .box-item {
      width: 8rem;
      height: 8rem;
      background-color: blue;
    }

    .m-drawer {
      background-color: #6d9cef;
      opacity: 0.8;

      .el-drawer__header {
        background-color: #6d9cef;
        border: none;
      }
    }
  }

  .showroom-3d-layer-modellist {
    top: 0;
    z-index: 11;
    height: 100%;
    position: absolute;
  }

  .showroom-3d-layer-attribute {
    top: 0;
    z-index: 11;
    left: 100%;
    height: 100%;
    position: absolute;
  }

  .showroom-3d-layer-operation {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 11;
    opacity: 0.7;

    .operation-btn-box {
      width: 5.88rem;
      height: 2.55rem;
      border-radius: 0.99rem;
      margin: 1rem 0.77rem;
      background-color: rgb(42, 3, 59);
      color: #fff;
    }
  }
}
</style>